#include "edit_text.h"
#include <Windows.h>

#define BACKSPACE_KEY	8

EditText::EditText(const Font & font, size_t char_size) :
	Text(),
	_caret(),
	_string(),
	_caret_pos(0U),
	_draw_caret(false)
{
	setFont(font);
	setCharSize(char_size);
}

EditText::~EditText()
{
}

void EditText::setCharSize(size_t char_size)
{
	setCharacterSize(char_size);
	_caret.setSize(Vector2f(3.f, static_cast<float>(char_size)));
}

bool EditText::handleEnteredKey(wchar_t unicode)
{
	if(unicode == BACKSPACE_KEY)
	{
		if(_caret_pos > 0U)
		{
			_string.erase(_caret_pos - 1);
			--_caret_pos;
		}
	}
	else if(unicode == L'\r')
	{
		return false;
	}
	else if(unicode == L'\x1b')
	{
		return false;
	}
	else if(unicode == 22)
	{
		if( !OpenClipboard( NULL ) ) return false;
		HANDLE handle = GetClipboardData( CF_UNICODETEXT );
		if( handle )
		{
			// Convert the ANSI string to Unicode, then
			// insert to our buffer.
			WCHAR* pwszText = ( WCHAR* )GlobalLock( handle );
			if( pwszText )
			{
				// Copy all characters up to null.
				size_t len = wcslen(pwszText);
				for(size_t i = 0U; i < len; ++i)
				{	
					_string.insert(_caret_pos, pwszText[i]);
					++_caret_pos;
				}
				GlobalUnlock( handle );
			}
		}
		CloseClipboard(); 
	}
	else
	{
		_string.insert(_caret_pos, unicode);
		++_caret_pos;
	}
	
	setString(_string);

	updateCaret();

	return true;
}

bool EditText::handleKeyPress(Event::KeyEvent key)
{
	if(key.code == Keyboard::Left)
	{
		if(_caret_pos > 0U)
			--_caret_pos;
	}
	else if(key.code == Keyboard::Right)
	{
		if(_caret_pos < _string.getSize())
			++_caret_pos;
	}
	else if(key.code == Keyboard::Delete)
	{
		if(_caret_pos < _string.getSize())
		{
			_string.erase(_caret_pos);
			setString(_string);
		}
	}
	else
	{
		return false;
	}

	updateCaret();

	return true;
}

void EditText::updateCaret()
{
	if(getString().isEmpty()) _caret.setPosition(	getPosition().x,
													getPosition().y + 5.f);
	else _caret.setPosition(findCharacterPos(_caret_pos).x,
							getPosition().y + 5.f);
}

void EditText::draw(RenderTarget& target, RenderStates states) const
{
	Text::draw(target, states);
	if(_draw_caret) target.draw(_caret, states);
}